<script setup lang="ts">
import type { Comment, ResponseData } from '@/types';
import { computed, ref, watch } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import Row from './Row.vue';
import type { UploadProps, UploadUserFile } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
import { http } from '@/services/http';
import { API_ROOT } from '@/types/constant';

const dialogVisible = ref(false);
const commentId = ref(0);
const commentForm = defineModel<Comment>({ required: true });
const emit = defineEmits(['commentId', 'comment-submitted']);
const dialogImageUrl = ref('');
const dialogRecommentVisible = defineModel<boolean>('recommentDialog');

const imgUrl = computed(() => {
  return commentForm.value.fileList.map((file) => ({
    name: file.name,
    url: `${API_ROOT}/upload/${file.name}`,
    raw: file.raw, // 确保每个文件对象都有 raw 属性
  }));
});

const handleFileChange = (file: { raw: any }, fileList: any[]) => {
  commentForm.value.fileList = fileList.map((item) => ({
    ...item,
    raw: item.raw || file.raw, // 确保每个文件对象都有 raw 属性
  }));
};

const handleCommentX = () => {
  const formData = new FormData();

  
  // 将表单数据转换为JSON字符串
  const formDataJson = {
    book_name: commentForm.value.book_name,
    book_img: commentForm.value.book_img,
    transaction_date: commentForm.value.transaction_date,
    rate: commentForm.value.rate,
    order_id: commentForm.value.order_id,
    content: commentForm.value.content,
    comment_id: commentForm.value.id,
  };

  // 添加JSON数据
  formData.append('formData', JSON.stringify(formDataJson));

  // 添加文件
  if (commentForm.value.fileList && commentForm.value.fileList.length > 0) {
    commentForm.value.fileList.forEach((file) => {
      if (file.raw) {
        formData.append('imgFiles', file.raw);
      }
    });
  }

  // 调试输出
  for (let pair of formData.entries()) {
    console.log(pair[0] + ':', pair[1]);
  }

  http
    .post('/comment/recreate', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        // 移除其他可能影响的headers
      },
      // 添加以下配置确保正确处理FormData
      transformRequest: [(data) => data],
    })
    .then((res) => {
      if (res.flag) {
        ElMessage({ type: 'success', message: res.msg });
        commentId.value = res.data;
        dialogRecommentVisible.value = false;
        commentForm.value.content = '';
        commentForm.value.rate = 0;
        commentForm.value.fileList = [];
        emit('commentId', commentForm.value.id);
      } else {
        ElMessage({ type: 'error', message: res.msg || '添加失败' });
      }
    })
    .catch(() => {
      ElMessage({ type: 'error', message: '请求失败，请稍后再试' });
    });
};
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};

const handleBeforeClose = (done: () => void) => {
  if (commentForm.value.content || commentForm.value.fileList.length > 0 || commentForm.value.rate) {
    ElMessageBox.confirm('如果退出评论，评论数据将会清空，是否继续？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        // 清空表单数据
        Object.assign(commentForm.value, {
          imgList: '',
          hasRecommented: false,
          id: 0,
          order_id: 0,
          rate: 0,
          content: '',
          fileList: [],
          book_img: '',
        });
        done();
      })
      .catch(() => {
        // 取消关闭
        dialogRecommentVisible.value = true; // 重新打开对话框
      });
  } else {
    done();
  }
};
const handleCancel = () => {
  handleBeforeClose(() => {
    dialogRecommentVisible.value = false;
  });
};

const check = ref(0);

watch(dialogRecommentVisible, (newVal) => {
  if (newVal === false) {
    if (check.value === 0) {
      console.log(1111);

      handleBeforeClose(() => {
        // 关闭对话框
      });
    }
  }
});
</script>

<template>
  <el-dialog
    title="追评信息"
    v-model="dialogRecommentVisible"
    width="50%"
    draggable
    overflow
    @before-close="handleBeforeClose"
  >
    <div class="row-container">
      <Row label="书本名称:" :content="commentForm.book_name" />
      <Row label="交易日期:" :content="commentForm.transaction_date" />

      <el-form-item label="评价等级">
        <el-rate
          v-model="commentForm.rate"
          :texts="['重开吧', '真心一般', '就那样', '有点东西', '牛杯666']"
          show-text
        />
      </el-form-item>
      <el-form-item label="上传图片:">
        <el-upload
          v-model:file-list="commentForm.fileList"
          name="imgFile"
          action="http://localhost:8080/comment/upload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="评价内容:">
        <el-input
          v-model="commentForm.content"
          style="width: 500px"
          :autosize="{ minRows: 6, maxRows: 8 }"
          type="textarea"
          placeholder="商家态度、书本质量、你觉得任何想要吐槽或者赞美的点"
        />
      </el-form-item>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleCommentX">提交</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.row-container {
  display: flex;
  flex-direction: column;
  gap: 16px; /* 间距 */
  padding: 20px;
  background-color: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 行样式 */
.row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #ebeef5;
}

.row:last-child {
  border-bottom: none;
}

.row label {
  font-weight: bold;
  margin-right: 16px;
}

/* 表单项样式 */
.el-form-item {
  margin-bottom: 16px;
}

.el-form-item__label {
  font-weight: bold;
}

/* 评分组件样式 */
.el-rate {
  display: flex;
  align-items: center;
}

.el-rate__text {
  margin-left: 8px;
}

/* 文本区域样式 */
.el-textarea {
  width: 100%;
}

/* 按钮样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
}

.el-button {
  padding: 10px 20px;
  border-radius: 4px;
}

.el-button--primary {
  background-color: #409eff;
  color: #fff;
}

.el-button--default {
  background-color: #fff;
  color: #606266;
  border: 1px solid #dcdfe6;
}
</style>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;

  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
